package com.iotimc.attendancesystem.base;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.lang.ref.WeakReference;

/**
 *
 * @author david
 * @date 2018/2/7
 */

public abstract class BaseDataBindingFragment<T extends ViewDataBinding> extends Fragment {
    private WeakReference<T> mBindingWeakReference;
    /**
     * 获取布局layout
     * @return
     */
    protected abstract int getResId();

    public T getBinding() {
        return mBindingWeakReference.get();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mBindingWeakReference == null || mBindingWeakReference.get() == null) {
            T viewDataBinding = DataBindingUtil.inflate(inflater,getResId(), container, false);
            mBindingWeakReference = new WeakReference<>(viewDataBinding);
        } else {
            ViewGroup parent = (ViewGroup) getBinding().getRoot().getParent();
            if (parent != null) {
                parent.removeView(getBinding().getRoot());
            }
        }
        return getBinding().getRoot();
    }
}
